package com.gs.common.tool.utils;


import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

/**
 * 文件工具类
 *
 * @author: guoshuai
 * @date: 2024/07/12 11:47
 **/
@Slf4j
public class FileUtil {


    /**
     * 创建xml文件
     *
     * @param doc      文档
     * @param filePath 文件路径
     * @param fileName 文件名
     * @param encoding 编码
     * @date 2024/07/15 11:18
     **/
    public static void generateXmlFile(Document doc, String filePath, String fileName, String encoding) {
        checkFilePath(filePath);
        //实际文件路径
        String actualFilePath = String.format("%s%s%s.xml", filePath, File.separator, fileName);
        // 创建输出格式
        //OutputFormat format = OutputFormat.createPrettyPrint();
        OutputFormat outputFormat = new OutputFormat();
        outputFormat.setEncoding(StringUtil.isEmpty(encoding) ? "UTF-8" : encoding);
        outputFormat.setIndentSize(1);
        outputFormat.setNewlines(true);
        outputFormat.setTrimText(false);
        //outputFormat.setPadText(true);
        //format.setEncoding(System.getProperty("file.encoding"));
        try {
            XMLWriter writer = new XMLWriter(new FileWriter(actualFilePath), outputFormat);
            writer.write(doc);
            writer.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 校验文件路径
     *
     * @param filePath 文件路径
     */
    private static void checkFilePath(String filePath) {
        //目录不存在，则先创建目录
        Path path = Paths.get(filePath);
        if (Files.notExists(path)) {
            try {
                Files.createDirectories(path);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 将内容写入java文件
     * @param filePath 文件路径
     * @param content 文件内容
     * @date 2025/03/12 15:59
     **/
    public static void writeToJavaFile(String filePath, String content) {
        //先校验目录是否存在，不存在，则先创建目录，不然无法生成文件
        String fileDir = filePath.substring(0, filePath.lastIndexOf(File.separator));
        checkFilePath(fileDir);
        Path path = Paths.get(String.format("%s.java", filePath));
        try {
            //先删除，再创建
            Files.deleteIfExists(path);
            Files.createFile(path);
        } catch (IOException e) {
            log.error("文件{},创建失败!", path.getFileName());
            return;
        }
        String javaPath = String.format("%s.java", filePath);
        Arrays.stream(content.split("\n")).forEach(line -> {
            // 使用 FileOutputStream、OutputStreamWriter 和 BufferedWriter 的组合
            // 通过 OutputStreamWriter 指定编码，并通过 FileOutputStream 的构造函数参数 true 来开启追加模式
            try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(javaPath, true), StandardCharsets.UTF_8))) {
                writer.write(line);
                writer.newLine();
            } catch (IOException e) {
                throw new IllegalArgumentException(String.format("文件写入失败，原因：%s", e.getMessage()));
            }
        });
        //如果需要使用平台特定的换行符，可以考虑使用System.lineSeparator()
//        Arrays.stream(content.split("\n")).forEach(line -> {
//            try {
//                Files.writeString(path, String.format("%s\n", line), StandardCharsets.UTF_8, java.nio.file.StandardOpenOption.APPEND);
//            } catch (IOException e) {
//                throw new IllegalArgumentException(String.format("文件写入失败，原因：%s", e.getMessage()));
//            }
//        });
    }


    /**
     * 复制资源问题到指定目录
     * @param resourcePath	资源路径
     * @param targetDir	目的目录
     * @date 2025/09/26 11:21
     **/
    public static void copyResource(String resourcePath, File targetDir) throws IOException {
        InputStream is = Thread.currentThread().getClass().getResourceAsStream(resourcePath);
        if (is == null) {
            throw new IOException("资源未找到: " + resourcePath);
        }
        File file = new File(targetDir, Paths.get(resourcePath).getFileName().toString());
        FileOutputStream fos = new FileOutputStream(file);
        byte[] buffer = new byte[8192];
        int len;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        is.close();
    }
}
